{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第一步: 导入必备的工具包."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "source": [
    "# 从io工具包导入open方法\n",
    "from io import open\n",
    "# 用于字符规范化\n",
    "import unicodedata\n",
    "# 用于正则表达式\n",
    "import re\n",
    "# 用于随机生成数据\n",
    "import random\n",
    "# 用于构建网络结构和函数的torch工具包\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "# torch中预定义的优化方法工具包\n",
    "from torch import optim\n",
    "# 设备选择, 我们可以选择在cuda或者cpu上运行你的代码\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第二步: 对持久化文件中数据进行处理, 以满足模型训练要求."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 将指定语言中的词汇映射成数值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "source": [
    "# 起始标志\n",
    "SOS_token = 0\n",
    "# 结束标志\n",
    "EOS_token = 1\n",
    "\n",
    "class Lang:\n",
    "    def __init__(self, name):\n",
    "        \"\"\"初始化函数中参数name代表传入某种语言的名字\"\"\"\n",
    "        # 将name传入类中\n",
    "        self.name = name\n",
    "        # 初始化词汇对应自然数值的字典\n",
    "        self.word2index = {}\n",
    "        # 初始化自然数值对应词汇的字典, 其中0，1对应的SOS和EOS已经在里面了\n",
    "        self.index2word = {0: \"SOS\", 1: \"EOS\"}\n",
    "        # 初始化词汇对应的自然数索引，这里从2开始，因为0，1已经被开始和结束标志占用了\n",
    "        self.n_words = 2  \n",
    "\n",
    "    def addSentence(self, sentence):\n",
    "        \"\"\"添加句子函数, 即将句子转化为对应的数值序列, 输入参数sentence是一条句子\"\"\"\n",
    "        # 根据一般国家的语言特性(我们这里研究的语言都是以空格分个单词)\n",
    "        # 对句子进行分割，得到对应的词汇列表\n",
    "        for word in sentence.split(' '):\n",
    "            # 然后调用addWord进行处理\n",
    "            self.addWord(word)\n",
    "\n",
    "\n",
    "    def addWord(self, word):\n",
    "        \"\"\"添加词汇函数, 即将词汇转化为对应的数值, 输入参数word是一个单词\"\"\"\n",
    "        # 首先判断word是否已经在self.word2index字典的key中\n",
    "        if word not in self.word2index:\n",
    "            # 如果不在, 则将这个词加入其中, 并为它对应一个数值，即self.n_words\n",
    "            self.word2index[word] = self.n_words\n",
    "            # 同时也将它的反转形式加入到self.index2word中\n",
    "            self.index2word[self.n_words] = word\n",
    "            # self.n_words一旦被占用之后，逐次加1, 变成新的self.n_words\n",
    "            self.n_words += 1"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "source": [
    "# 调用验证==\n",
    "name = \"eng\"\n",
    "sentence = \"hello I am Jay\""
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "source": [
    "engl = Lang(name)\n",
    "engl.addSentence(sentence)\n",
    "print(\"word2index:\", engl.word2index)\n",
    "print(\"index2word:\", engl.index2word)\n",
    "print(\"n_words:\", engl.n_words)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 字符规范化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "source": [
    "# 将unicode转为Ascii, 我们可以认为是去掉一些语言中的重音标记：Ślusàrski\n",
    "def unicodeToAscii(s):\n",
    "    return ''.join(\n",
    "        c for c in unicodedata.normalize('NFD', s)\n",
    "        if unicodedata.category(c) != 'Mn'\n",
    "    )\n",
    "\n",
    "\n",
    "def normalizeString(s):\n",
    "    \"\"\"字符串规范化函数, 参数s代表传入的字符串\"\"\"\n",
    "    # 使字符变为小写并去除两侧空白符, z再使用unicodeToAscii去掉重音标记\n",
    "    s = unicodeToAscii(s.lower().strip())\n",
    "    # 在.!?前加一个空格\n",
    "    s = re.sub(r\"([.!?])\", r\" \\1\", s)\n",
    "    # 使用正则表达式将字符串中不是大小写字母和正常标点的都替换成空格\n",
    "    s = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n",
    "    return s"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "source": [
    "# 参数输入\n",
    "s = \"Are you kidding me?\"\n",
    "# 调用验证\n",
    "nsr = normalizeString(s)\n",
    "print(nsr)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 将持久化文件中的数据加载到内存, 并实例化类Lang"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "source": [
    "data_path = './data/eng-fra.txt'\n",
    "\n",
    "def readLangs(lang1, lang2):\n",
    "    \"\"\"读取语言函数, 参数lang1是源语言的名字, 参数lang2是目标语言的名字\n",
    "       返回对应的class Lang对象, 以及语言对列表\"\"\"\n",
    "    # 从文件中读取语言对并以/n划分存到列表lines中\n",
    "    lines = open(data_path, encoding='utf-8').\\\n",
    "        read().strip().split('\\n')\n",
    "    # print(\"lines===:\", lines)\n",
    "    # \"He looks pale. He must have drunk too much last night.\\tIl n'a pas l'air bien. Il a dû trop boire la nuit dernière.\"\n",
    "    # 对lines列表中的句子进行标准化处理，并以\\t进行再次划分, 形成子列表, 也就是语言对\n",
    "    pairs = [[normalizeString(s) for s in l.split('\\t')] for l in lines] \n",
    "    # 然后分别将语言名字传入Lang类中, 获得对应的语言对象, 返回结果\n",
    "    input_lang = Lang(lang1)\n",
    "    output_lang = Lang(lang2)\n",
    "    return input_lang, output_lang, pairs"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "source": [
    "# 参数输入\n",
    "lang1 = \"eng\"\n",
    "lang2 = \"fra\"\n",
    "# 调用验证\n",
    "input_lang, output_lang, pairs = readLangs(lang1, lang2)\n",
    "print(\"input_lang:\", input_lang)\n",
    "print(\"output_lang:\", output_lang)\n",
    "print(\"pairs中的前五个:\", pairs[:5])"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 过滤出符合我们要求的语言对"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "source": [
    "# 设置组成句子中单词或标点的最多个数\n",
    "MAX_LENGTH = 10\n",
    "\n",
    "# 选择带有指定前缀的语言特征数据作为训练数据\n",
    "eng_prefixes = (\n",
    "    \"i am \", \"i m \",\n",
    "    \"he is\", \"he s \",\n",
    "    \"she is\", \"she s \",\n",
    "    \"you are\", \"you re \",\n",
    "    \"we are\", \"we re \",\n",
    "    \"they are\", \"they re \"\n",
    ")\n",
    "\n",
    "\n",
    "def filterPair(p):\n",
    "    \"\"\"语言对过滤函数, 参数p代表输入的语言对, 如['she is afraid.', 'elle malade.']\"\"\"\n",
    "    # p[0]代表英语句子，对它进行划分，它的长度应小于最大长度MAX_LENGTH并且要以指定的前缀开头\n",
    "    # p[1]代表法文句子, 对它进行划分，它的长度应小于最大长度MAX_LENGTH\n",
    "    return len(p[0].split(' ')) < MAX_LENGTH and \\\n",
    "        p[0].startswith(eng_prefixes) and \\\n",
    "        len(p[1].split(' ')) < MAX_LENGTH \n",
    "\n",
    "\n",
    "def filterPairs(pairs):\n",
    "    \"\"\"对多个语言对列表进行过滤, 参数pairs代表语言对组成的列表, 简称语言对列表\"\"\"\n",
    "    # 函数中直接遍历列表中的每个语言对并调用filterPair即可\n",
    "    return [pair for pair in pairs if filterPair(pair)]"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "source": [
    "# 输入参数\n",
    "# 输入参数pairs使用readLangs函数的输出结果pairs\n",
    "fpairs = filterPairs(pairs)\n",
    "print(\"过滤后的pairs前五个:\", fpairs[:5])"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 对以上数据准备函数进行整合, 并使用类Lang对语言对进行数值映射"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "source": [
    "def prepareData(lang1, lang2):\n",
    "    \"\"\"数据准备函数, 完成将所有字符串数据向数值型数据的映射以及过滤语言对\n",
    "       参数lang1, lang2分别代表源语言和目标语言的名字\"\"\"\n",
    "    # 首先通过readLangs函数获得input_lang, output_lang对象，以及字符串类型的语言对列表\n",
    "    input_lang, output_lang, pairs = readLangs(lang1, lang2)\n",
    "    # 对字符串类型的语言对列表进行过滤操作\n",
    "    pairs = filterPairs(pairs)\n",
    "    # 对过滤后的语言对列表进行遍历\n",
    "    for pair in pairs:\n",
    "        # 并使用input_lang和output_lang的addSentence方法对其进行数值映射\n",
    "        input_lang.addSentence(pair[0])\n",
    "        output_lang.addSentence(pair[1])\n",
    "    # 返回数值映射后的对象, 和过滤后语言对\n",
    "    return input_lang, output_lang, pairs"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "source": [
    "# 调用验证\n",
    "input_lang, output_lang, pairs = prepareData('eng', 'fra')\n",
    "print(\"input_n_words:\", input_lang.n_words)\n",
    "print(\"output_n_words:\", output_lang.n_words)\n",
    "print(random.choice(pairs))"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 将语言对转化为模型输入需要的张量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "source": [
    "def tensorFromSentence(lang, sentence):\n",
    "    \"\"\"将文本句子转换为张量, 参数lang代表传入的Lang的实例化对象, sentence是预转换的句子\"\"\"\n",
    "    # 对句子进行分割并遍历每一个词汇, 然后使用lang的word2index方法找到它对应的索引\n",
    "    # 这样就得到了该句子对应的数值列表\n",
    "    indexes = [lang.word2index[word] for word in sentence.split(' ')]\n",
    "    # 然后加入句子结束标志\n",
    "    indexes.append(EOS_token)\n",
    "    # 将其使用torch.tensor封装成张量, 并改变它的形状为nx1, 以方便后续计算\n",
    "    return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)\n",
    "\n",
    "\n",
    "def tensorsFromPair(pair):\n",
    "    \"\"\"将语言对转换为张量对, 参数pair为一个语言对\"\"\"\n",
    "    # 调用tensorFromSentence分别将源语言和目标语言分别处理，获得对应的张量表示\n",
    "    input_tensor = tensorFromSentence(input_lang, pair[0])\n",
    "    target_tensor = tensorFromSentence(output_lang, pair[1])\n",
    "    # 最后返回它们组成的元组\n",
    "    return (input_tensor, target_tensor)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "source": [
    "# 输入参数\n",
    "# 取pairs的第一条 形状为['i m curious .', 'je suis curieux .']，pairs[0]为英文， pairs[1]为法文\n",
    "pair = pairs[0]"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "source": [
    "pair_tensor = tensorsFromPair(pair)\n",
    "print(pair_tensor)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第三步: 构建基于GRU的编码器和解码器."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构建基于GRU的编码器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "编码器结构图"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](http://52.83.69.131:8002/img/encoder-network.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "source": [
    "class EncoderRNN(nn.Module):\n",
    "    def __init__(self, input_size, hidden_size):\n",
    "        \"\"\"它的初始化参数有两个, input_size代表解码器的输入尺寸即源语言的\n",
    "            词表大小，hidden_size代表GRU的隐层节点数, 也代表词嵌入维度, 同时又是GRU的输入尺寸\"\"\"\n",
    "        super(EncoderRNN, self).__init__()\n",
    "        # 将参数hidden_size传入类中\n",
    "        self.hidden_size = hidden_size\n",
    "        # 实例化nn中预定义的Embedding层, 它的参数分别是input_size, hidden_size\n",
    "        # 这里的词嵌入维度即hidden_size\n",
    "        # nn.Embedding的演示在该代码下方\n",
    "        self.embedding = nn.Embedding(input_size, hidden_size)\n",
    "        # 然后实例化nn中预定义的GRU层, 它的参数是hidden_size\n",
    "        # nn.GRU的演示在该代码下方\n",
    "        self.gru = nn.GRU(hidden_size, hidden_size)\n",
    "\n",
    "    def forward(self, input, hidden):\n",
    "        \"\"\"编码器前向逻辑函数中参数有两个, input代表源语言的Embedding层输入张量\n",
    "           hidden代表编码器层gru的初始隐层张量\"\"\"\n",
    "        # 将输入张量进行embedding操作, 并使其形状变为(1,1,-1),-1代表自动计算维度\n",
    "        # 理论上，我们的编码器每次只以一个词作为输入, 因此词汇映射后的尺寸应该是[1, embedding]\n",
    "        # 而这里转换成三维的原因是因为torch中预定义gru必须使用三维张量作为输入, 因此我们拓展了一个维度\n",
    "        output = self.embedding(input).view(1, 1, -1)\n",
    "        # 然后将embedding层的输出和传入的初始hidden作为gru的输入传入其中, \n",
    "        # 获得最终gru的输出output和对应的隐层张量hidden， 并返回结果\n",
    "        output, hidden = self.gru(output, hidden)\n",
    "        return output, hidden\n",
    "\n",
    "    def initHidden(self):\n",
    "        \"\"\"初始化隐层张量函数\"\"\"\n",
    "        # 将隐层张量初始化成为1x1xself.hidden_size大小的0张量\n",
    "        return torch.zeros(1, 1, self.hidden_size, device=device)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "source": [
    "# 扩展view的使用\n",
    "x = torch.randn(4, 4)\n",
    "x"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "source": [
    "y = x.view(16)\n",
    "y "
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "source": [
    "# 参数中的-1就代表这个位置由其他位置的数字来推断，只要在不致歧义的情况的下，\n",
    "# view参数就可以推断出来，也就是人可以推断出形状的情况下，view函数也可以推断出来\n",
    "z = x.view(-1, 8)\n",
    "z "
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "source": [
    "# 把原先tensor中的数据按照行优先的顺序排成一个一维的数据，\n",
    "# 然后按照参数组合成其他维度的tensor\n",
    "a = x.view(2, 2, 4)\n",
    "a "
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "source": [
    "# 实例化参数并输入\n",
    "hidden_size = 25\n",
    "input_size = 20\n",
    "# pair_tensor[0]代表源语言即英文的句子，pair_tensor[0][0]代表句子中\n",
    "# 的第一个词\n",
    "input = pair_tensor[0][0]\n",
    "# 初始化第一个隐层张量，1x1xhidden_size的0张量\n",
    "hidden = torch.zeros(1, 1, hidden_size)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "source": [
    "# 调用并验证\n",
    "encoder = EncoderRNN(input_size, hidden_size)\n",
    "encoder_output, hidden = encoder(input, hidden)\n",
    "print(encoder_output)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构建基于GRU的解码器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "解码器结构图"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](http://52.83.69.131:8002/img/decoder-network.png)\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "source": [
    "class DecoderRNN(nn.Module):\n",
    "    def __init__(self, hidden_size, output_size):\n",
    "        \"\"\"初始化函数有两个参数，hidden_size代表解码器中GRU的输入尺寸，也是它的隐层节点数\n",
    "           output_size代表整个解码器的输出尺寸, 也是我们希望得到的指定尺寸即目标语言的词表大小\"\"\"\n",
    "        super(DecoderRNN, self).__init__()\n",
    "        # 将hidden_size传入到类中\n",
    "        self.hidden_size = hidden_size\n",
    "        # 实例化一个nn中的Embedding层对象, 它的参数output这里表示目标语言的词表大小\n",
    "        # hidden_size表示目标语言的词嵌入维度\n",
    "        self.embedding = nn.Embedding(output_size, hidden_size)\n",
    "        # 实例化GRU对象，输入参数都是hidden_size，代表它的输入尺寸和隐层节点数相同\n",
    "        self.gru = nn.GRU(hidden_size, hidden_size)\n",
    "#         # 注意: 这里的15是原来的hidden_size是可以任意修改的， \n",
    "#         #和GRU第二个参数的hidden_size是不一样的， GRU的第二参数hidden_size必须是传入的参数hidden_size\n",
    "#         # 这里的input_size是对应的词映射为对应张量的值 即input== tensor([2])， 这里是一个词对应的张量值， 所以后面尺寸才是[1, 15]\n",
    "#         self.embedding = nn.Embedding(input_size, 15)\n",
    "#         self.gru = nn.GRU(15, hidden_size)\n",
    "        \n",
    "        # 实例化线性层, 对GRU的输出做线性变化, 获我们希望的输出尺寸output_size\n",
    "        # 因此它的两个参数分别是hidden_size, output_size\n",
    "        self.out = nn.Linear(hidden_size, output_size)\n",
    "        # 最后使用softmax进行处理，以便于分类\n",
    "        self.softmax = nn.LogSoftmax(dim=1)\n",
    "\n",
    "\n",
    "    def forward(self, input, hidden):\n",
    "        \"\"\"解码器的前向逻辑函数中, 参数有两个, input代表目标语言的Embedding层输入张量\n",
    "           hidden代表解码器GRU的初始隐层张量\"\"\"\n",
    "        # 将输入张量进行embedding操作, 并使其形状变为(1,1,-1),-1代表自动计算维度\n",
    "        # 原因和解码器相同，因为torch预定义的GRU层只接受三维张量作为输入\n",
    "        output = self.embedding(input).view(1, 1, -1)\n",
    "        # 然后使用relu函数对输出进行处理，根据relu函数的特性, 将使Embedding矩阵更稀疏，以防止过拟合\n",
    "        output = F.relu(output)\n",
    "        # 接下来, 将把embedding的输出以及初始化的hidden张量传入到解码器gru中\n",
    "        output, hidden = self.gru(output, hidden)\n",
    "        # 因为GRU输出的output也是三维张量，第一维没有意义，因此可以通过output[0]来降维\n",
    "        # 再传给线性层做变换, 最后用softmax处理以便于分类\n",
    "        # 思考点： # 试试这里不进行降维可以否, 可以不降维度， 但是效果不明显\n",
    "        output = self.softmax(self.out(output[0]))\n",
    "        return output, hidden\n",
    "\n",
    "    def initHidden(self):\n",
    "        \"\"\"初始化隐层张量函数\"\"\"\n",
    "        # 将隐层张量初始化成为1x1xself.hidden_size大小的0张量\n",
    "        return torch.zeros(1, 1, self.hidden_size, device=device)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "source": [
    "# 实例化参数并输入\n",
    "hidden_size = 25\n",
    "output_size = 10\n",
    "# pair_tensor[1]代表目标语言即法文的句子，\n",
    "# pair_tensor[1][0]代表句子中的第一个词\n",
    "input = pair_tensor[1][0]\n",
    "# 初始化第一个隐层张量，1x1xhidden_size的0张量\n",
    "hidden = torch.zeros(1, 1, hidden_size)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "source": [
    "# 调用并验证\n",
    "decoder = DecoderRNN(hidden_size, output_size)\n",
    "output, hidden = decoder(input, hidden)\n",
    "print(output)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构建基于GRU和Attention的解码器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "解码器结构图"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](http://52.83.69.131:8002/img/attention-decoder-network.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "source": [
    "class AttnDecoderRNN(nn.Module):\n",
    "    def __init__(self, hidden_size, output_size, dropout_p=0.1, max_length=MAX_LENGTH):\n",
    "        \"\"\"初始化函数中的参数有4个, hidden_size代表解码器中GRU的输入尺寸，也是它的隐层节点数\n",
    "           output_size代表整个解码器的输出尺寸, 也是我们希望得到的指定尺寸即目标语言的词表大小\n",
    "           dropout_p代表我们使用dropout层时的置零比率，默认0.1, max_length代表句子的最大长度\"\"\"\n",
    "        super(AttnDecoderRNN, self).__init__()\n",
    "        # 将以下参数传入类中\n",
    "        self.hidden_size = hidden_size\n",
    "        self.output_size = output_size\n",
    "        self.dropout_p = dropout_p\n",
    "        self.max_length = max_length\n",
    "\n",
    "        # 实例化一个Embedding层, 输入参数是self.output_size和self.hidden_size\n",
    "        self.embedding = nn.Embedding(self.output_size, self.hidden_size)\n",
    "        # 根据attention的QKV理论，attention的输入参数为三个Q，K，V，\n",
    "        # 第一步，使用Q与K进行attention权值计算得到权重矩阵, 再与V做矩阵乘法, 得到V的注意力表示结果.\n",
    "        # 这里常见的计算方式有三种:\n",
    "        # 1，将Q，K进行纵轴拼接, 做一次线性变化, 再使用softmax处理获得结果最后与V做张量乘法\n",
    "        # 2，将Q，K进行纵轴拼接, 做一次线性变化后再使用tanh函数激活, 然后再进行内部求和, 最后使用softmax处理获得结果再与V做张量乘法\n",
    "        # 3，将Q与K的转置做点积运算, 然后除以一个缩放系数, 再使用softmax处理获得结果最后与V做张量乘法\n",
    "\n",
    "        # 说明：当注意力权重矩阵和V都是三维张量且第一维代表为batch条数时, 则做bmm运算.\n",
    "\n",
    "        # 第二步, 根据第一步采用的计算方法, 如果是拼接方法，则需要将Q与第二步的计算结果再进行拼接, \n",
    "        # 如果是转置点积, 一般是自注意力, Q与V相同, 则不需要进行与Q的拼接.因此第二步的计算方式与第一步采用的全值计算方法有关.\n",
    "        # 第三步，最后为了使整个attention结构按照指定尺寸输出, 使用线性层作用在第二步的结果上做一个线性变换. 得到最终对Q的注意力表示.\n",
    "\n",
    "        # 我们这里使用的是第一步中的第一种计算方式, 因此需要一个线性变换的矩阵, 实例化nn.Linear\n",
    "        # 因为它的输入是Q，K的拼接, 所以输入的第一个参数是self.hidden_size * 2，第二个参数是self.max_length\n",
    "        # 这里的Q是解码器的Embedding层的输出, K是解码器GRU的隐层输出，因为首次隐层还没有任何输出，会使用编码器的隐层输出\n",
    "        # 而这里的V是编码器层的输出\n",
    "        self.attn = nn.Linear(self.hidden_size * 2, self.max_length)\n",
    "        # 接着我们实例化另外一个线性层, 它是attention理论中的第四步的线性层，用于规范输出尺寸\n",
    "        # 这里它的输入来自第三步的结果, 因为第三步的结果是将Q与第二步的结果进行拼接, 因此输入维度是self.hidden_size * 2\n",
    "        self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)\n",
    "        # 接着实例化一个nn.Dropout层，并传入self.dropout_p\n",
    "        self.dropout = nn.Dropout(self.dropout_p)\n",
    "        # 之后实例化nn.GRU, 它的输入和隐层尺寸都是self.hidden_size\n",
    "        self.gru = nn.GRU(self.hidden_size, self.hidden_size)\n",
    "        # 最后实例化gru后面的线性层，也就是我们的解码器输出层.\n",
    "        self.out = nn.Linear(self.hidden_size, self.output_size)\n",
    "\n",
    "\n",
    "    def forward(self, input, hidden, encoder_outputs):\n",
    "        \"\"\"forward函数的输入参数有三个, 分别是源数据输入张量, 初始的隐层张量, 以及解码器的输出张量\"\"\"\n",
    "\n",
    "        # 根据结构计算图, 输入张量进行Embedding层并扩展维度\n",
    "        embedded = self.embedding(input).view(1, 1, -1)\n",
    "        # 使用dropout进行随机丢弃，防止过拟合\n",
    "        embedded = self.dropout(embedded)\n",
    "\n",
    "        # 进行attention的权重计算, 哦我们呢使用第一种计算方式：\n",
    "        # 将Q，K进行纵轴拼接, 做一次线性变化, 最后使用softmax处理获得结果\n",
    "        attn_weights = F.softmax(\n",
    "            self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1)\n",
    "\n",
    "        # 然后进行第一步的后半部分, 将得到的权重矩阵与V做矩阵乘法计算, 当二者都是三维张量且第一维代表为batch条数时, 则做bmm运算\n",
    "        attn_applied = torch.bmm(attn_weights.unsqueeze(0),\n",
    "                                 encoder_outputs.unsqueeze(0))\n",
    "\n",
    "        # 之后进行第二步, 通过取[0]是用来降维, 根据第一步采用的计算方法, 需要将Q与第一步的计算结果再进行拼接\n",
    "        output = torch.cat((embedded[0], attn_applied[0]), 1)\n",
    "\n",
    "        # 最后是第三步, 使用线性层作用在第三步的结果上做一个线性变换并扩展维度，得到输出\n",
    "        output = self.attn_combine(output).unsqueeze(0)\n",
    "\n",
    "        # attention结构的结果使用relu激活\n",
    "        output = F.relu(output)\n",
    "\n",
    "        # 将激活后的结果作为gru的输入和hidden一起传入其中\n",
    "        output, hidden = self.gru(output, hidden)\n",
    "\n",
    "        # 最后将结果降维并使用softmax处理得到最终的结果\n",
    "        output = F.log_softmax(self.out(output[0]), dim=1)\n",
    "        # 返回解码器结果，最后的隐层张量以及注意力权重张量\n",
    "        return output, hidden, attn_weights\n",
    "\n",
    "    def initHidden(self):\n",
    "        \"\"\"初始化隐层张量函数\"\"\"\n",
    "        # 将隐层张量初始化成为1x1xself.hidden_size大小的0张量\n",
    "        return torch.zeros(1, 1, self.hidden_size, device=device)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "source": [
    "# 实例化参数并输入\n",
    "hidden_size = 25\n",
    "output_size = 10\n",
    "input = pair_tensor[1][0]\n",
    "hidden = torch.zeros(1, 1, hidden_size)\n",
    "# encoder_outputs需要是encoder中每一个时间步的输出堆叠而成\n",
    "# 它的形状应该是10x25, 我们这里直接随机初始化一个张量\n",
    "encoder_outputs  = torch.randn(10, 25)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "source": [
    "# 调用并验证\n",
    "decoder = AttnDecoderRNN(hidden_size, output_size)\n",
    "output, hidden, attn_weights= decoder(input, hidden, encoder_outputs)\n",
    "print(output)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第四步: 构建模型训练函数, 并进行训练."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构建训练函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "source": [
    "# 设置teacher_forcing比率为0.5\n",
    "teacher_forcing_ratio = 0.5\n",
    "\n",
    "\n",
    "def train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):\n",
    "    \"\"\"训练函数, 输入参数有8个, 分别代表input_tensor：源语言输入张量，target_tensor：目标语言输入张量，encoder, decoder：编码器和解码器实例化对象\n",
    "       encoder_optimizer, decoder_optimizer：编码器和解码器优化方法，criterion：损失函数计算方法，max_length：句子的最大长度\"\"\"\n",
    "\n",
    "    # 初始化隐层张量\n",
    "    encoder_hidden = encoder.initHidden()\n",
    "\n",
    "    # 编码器和解码器优化器梯度归0\n",
    "    encoder_optimizer.zero_grad()\n",
    "    decoder_optimizer.zero_grad()\n",
    "    \n",
    "#     print('input_tensor==', input_tensor)\n",
    "#     '''\n",
    "#     input_tensor== tensor([[  2],\n",
    "#         [  3],\n",
    "#         [800],\n",
    "#         [  4],\n",
    "#         [  1]])\n",
    "#     '''\n",
    "\n",
    "    # 根据源文本和目标文本张量获得对应的长度\n",
    "    input_length = input_tensor.size(0)\n",
    "    target_length = target_tensor.size(0)\n",
    "    \n",
    "#     input_length = input_tensor.size(0)\n",
    "#     print('input_length==', input_length) # input_length== 5\n",
    "#     target_length = target_tensor.size(0)\n",
    "#     print('target_length==', target_length) # target_length== 6\n",
    "\n",
    "    # 初始化编码器输出张量，形状是max_lengthxencoder.hidden_size的0张量\n",
    "    encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n",
    "\n",
    "    # 初始设置损失为0\n",
    "    loss = 0\n",
    "\n",
    "    # 循环遍历输入张量索引\n",
    "    for ei in range(input_length):\n",
    "        # print('ei------', ei)\n",
    "        # 根据索引从input_tensor取出对应的单词的张量表示，和初始化隐层张量一同传入encoder对象中\n",
    "        encoder_output, encoder_hidden = encoder(\n",
    "            input_tensor[ei], encoder_hidden)\n",
    "#         print('encoder_output-----', encoder_output) # 形状为[1, 1, hidden_size], 所以下面直接来[0, 0]进行提取\n",
    "        # 将每次获得的输出encoder_output(三维张量), 使用[0, 0]降两维变成向量依次存入到encoder_outputs\n",
    "        # 这样encoder_outputs每一行存的都是对应的句子中每个单词通过编码器的输出结果\n",
    "        encoder_outputs[ei] = encoder_output[0, 0]\n",
    "#     print('encoder_outputs++++++', encoder_outputs)\n",
    "#     print('encoder_outputsshape++++++', encoder_outputs.shape) # encoder_outputsshape++++++ torch.Size([10, 256])\n",
    "        \n",
    "    # 初始化解码器的第一个输入，即起始符\n",
    "    decoder_input = torch.tensor([[SOS_token]], device=device)\n",
    "\n",
    "    # 初始化解码器的隐层张量即编码器的隐层输出\n",
    "    decoder_hidden = encoder_hidden\n",
    "\n",
    "    # 根据随机数与teacher_forcing_ratio对比判断是否使用teacher_forcing\n",
    "    use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n",
    "\n",
    "    # 如果使用teacher_forcing\n",
    "    if use_teacher_forcing:\n",
    "        # 循环遍历目标张量索引\n",
    "        for di in range(target_length):\n",
    "            # 将decoder_input, decoder_hidden, encoder_outputs即attention中的QKV, \n",
    "            # 传入解码器对象, 获得decoder_output, decoder_hidden, decoder_attention\n",
    "            decoder_output, decoder_hidden, decoder_attention = decoder(\n",
    "                decoder_input, decoder_hidden, encoder_outputs)\n",
    "            # 因为使用了teacher_forcing, 无论解码器输出的decoder_output是什么, 我们都只\n",
    "            # 使用‘正确的答案’，即target_tensor[di]来计算损失\n",
    "            loss += criterion(decoder_output, target_tensor[di])\n",
    "            # 并强制将下一次的解码器输入设置为‘正确的答案’\n",
    "            decoder_input = target_tensor[di]  \n",
    "\n",
    "    else:\n",
    "        # 如果不使用teacher_forcing\n",
    "        # 仍然遍历目标张量索引\n",
    "        for di in range(target_length):\n",
    "            # 将decoder_input, decoder_hidden, encoder_outputs传入解码器对象\n",
    "            # 获得decoder_output, decoder_hidden, decoder_attention\n",
    "            decoder_output, decoder_hidden, decoder_attention = decoder(\n",
    "                decoder_input, decoder_hidden, encoder_outputs)\n",
    "            # 只不过这里我们将从decoder_output取出答案\n",
    "            topv, topi = decoder_output.topk(1)\n",
    "            # 损失计算仍然使用decoder_output和target_tensor[di]\n",
    "            loss += criterion(decoder_output, target_tensor[di])\n",
    "            # 最后如果输出值是终止符，则循环停止\n",
    "            if topi.squeeze().item() == EOS_token:\n",
    "                break\n",
    "            # 否则，并对topi降维并分离赋值给decoder_input以便进行下次运算\n",
    "            # 这里的detach的分离作用使得这个decoder_input与模型构建的张量图无关，相当于全新的外界输入\n",
    "            decoder_input = topi.squeeze().detach()\n",
    "\n",
    "\n",
    "    # 误差进行反向传播\n",
    "    loss.backward()\n",
    "    # 编码器和解码器进行优化即参数更新\n",
    "    encoder_optimizer.step()\n",
    "    decoder_optimizer.step()\n",
    "\n",
    "    # 最后返回平均损失\n",
    "    return loss.item() / target_length"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构建时间计算函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "source": [
    "# 导入时间和数学工具包\n",
    "import time\n",
    "import math\n",
    "\n",
    "def timeSince(since):\n",
    "    \"获得每次打印的训练耗时, since是训练开始时间\"\n",
    "    # 获得当前时间\n",
    "    now = time.time()\n",
    "    # 获得时间差，就是训练耗时\n",
    "    s = now - since\n",
    "    # 将秒转化为分钟, 并取整\n",
    "    m = math.floor(s / 60)\n",
    "    # 计算剩下不够凑成1分钟的秒数\n",
    "    s -= m * 60\n",
    "    # 返回指定格式的耗时\n",
    "    return '%dm %ds' % (m, s)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "source": [
    "# 实例化参数\n",
    "# 假定模型训练开始时间是10min之前\n",
    "since = time.time() - 10*60\n",
    "\n",
    "# 调用验证\n",
    "period = timeSince(since)\n",
    "print(period)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 调用训练函数并打印日志和制图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "source": [
    "# 导入plt以便绘制损失曲线\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "def trainIters(encoder, decoder, n_iters, print_every=1000, plot_every=100, learning_rate=0.01):\n",
    "    \"\"\"训练迭代函数, 输入参数有6个，分别是encoder, decoder: 编码器和解码器对象，\n",
    "       n_iters: 总迭代步数, print_every:打印日志间隔, plot_every:绘制损失曲线间隔, learning_rate学习率\"\"\"\n",
    "    # 获得训练开始时间戳\n",
    "    start = time.time()\n",
    "    # 每个损失间隔的平均损失保存列表，用于绘制损失曲线\n",
    "    plot_losses = []\n",
    "\n",
    "    # 每个打印日志间隔的总损失，初始为0\n",
    "    print_loss_total = 0  \n",
    "    # 每个绘制损失间隔的总损失，初始为0\n",
    "    plot_loss_total = 0  \n",
    "\n",
    "    # 使用预定义的SGD作为优化器，将参数和学习率传入其中\n",
    "    encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)\n",
    "    decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)\n",
    "\n",
    "    # 选择损失函数\n",
    "    criterion = nn.NLLLoss()\n",
    "\n",
    "    # 根据设置迭代步进行循环\n",
    "    for iter in range(1, n_iters + 1):\n",
    "        # 每次从语言对列表中随机取出一条作为训练语句\n",
    "        training_pair = tensorsFromPair(random.choice(pairs))\n",
    "        # 分别从training_pair中取出输入张量和目标张量\n",
    "        input_tensor = training_pair[0]\n",
    "        target_tensor = training_pair[1]\n",
    "\n",
    "        # 通过train函数获得模型运行的损失\n",
    "        loss = train(input_tensor, target_tensor, encoder,\n",
    "                     decoder, encoder_optimizer, decoder_optimizer, criterion)\n",
    "        # 将损失进行累和\n",
    "        print_loss_total += loss\n",
    "        plot_loss_total += loss\n",
    "\n",
    "        # 当迭代步达到日志打印间隔时\n",
    "        if iter % print_every == 0:\n",
    "            # 通过总损失除以间隔得到平均损失\n",
    "            print_loss_avg = print_loss_total / print_every\n",
    "            # 将总损失归0\n",
    "            print_loss_total = 0\n",
    "            # 打印日志，日志内容分别是：训练耗时，当前迭代步，当前进度百分比，当前平均损失\n",
    "            print('%s (%d %d%%) %.4f' % (timeSince(start),\n",
    "                                         iter, iter / n_iters * 100, print_loss_avg))\n",
    "\n",
    "        # 当迭代步达到损失绘制间隔时\n",
    "        if iter % plot_every == 0:\n",
    "            # 通过总损失除以间隔得到平均损失\n",
    "            plot_loss_avg = plot_loss_total / plot_every\n",
    "            # 将平均损失装进plot_losses列表\n",
    "            plot_losses.append(plot_loss_avg)\n",
    "            # 总损失归0\n",
    "            plot_loss_total = 0\n",
    "\n",
    "    # 绘制损失曲线\n",
    "    plt.figure()  \n",
    "    plt.plot(plot_losses)\n",
    "    # 保存到指定路径\n",
    "    plt.savefig(\"./s2s_loss.png\")"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "source": [
    "# 设置隐层大小为256 ，也是词嵌入维度      \n",
    "hidden_size = 256\n",
    "# 通过input_lang.n_words获取输入词汇总数，与hidden_size一同传入EncoderRNN类中\n",
    "# 得到编码器对象encoder1\n",
    "encoder1 = EncoderRNN(input_lang.n_words, hidden_size).to(device)\n",
    "\n",
    "# 通过output_lang.n_words获取目标词汇总数，与hidden_size和dropout_p一同传入AttnDecoderRNN类中\n",
    "# 得到解码器对象attn_decoder1\n",
    "attn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1).to(device)\n",
    "\n",
    "# 设置迭代步数 \n",
    "n_iters = 75000\n",
    "# 设置日志打印间隔\n",
    "print_every = 5000 "
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [
    "# 调用trainIters进行模型训练，将编码器对象encoder1，码器对象attn_decoder1，迭代步数，日志打印间隔传入其中\n",
    "trainIters(encoder1, attn_decoder1, n_iters, print_every=print_every)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 保存模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [
    "# PATH = './seq2seq_eng2fra.pth'\n",
    "# torch.save(xx.state_dict(), PATH)???"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第五步: 构建模型评估函数, 并进行测试以及Attention效果分析."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构建模型评估函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "source": [
    "def evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):\n",
    "    \"\"\"评估函数，输入参数有4个，分别是encoder, decoder: 编码器和解码器对象，\n",
    "       sentence:需要评估的句子，max_length:句子的最大长度\"\"\"\n",
    "\n",
    "    # 评估阶段不进行梯度计算\n",
    "    with torch.no_grad():\n",
    "        # 对输入的句子进行张量表示\n",
    "        input_tensor = tensorFromSentence(input_lang, sentence)\n",
    "        # 获得输入的句子长度\n",
    "        input_length = input_tensor.size()[0]\n",
    "        # 初始化编码器隐层张量\n",
    "        encoder_hidden = encoder.initHidden()\n",
    "\n",
    "        # 初始化编码器输出张量，是max_lengthxencoder.hidden_size的0张量\n",
    "        encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n",
    "\n",
    "        # 循环遍历输入张量索引\n",
    "        for ei in range(input_length):\n",
    "             # 根据索引从input_tensor取出对应的单词的张量表示，和初始化隐层张量一同传入encoder对象中\n",
    "            encoder_output, encoder_hidden = encoder(input_tensor[ei],\n",
    "                                                     encoder_hidden)\n",
    "            #将每次获得的输出encoder_output(三维张量), 使用[0, 0]降两维变成向量依次存入到encoder_outputs\n",
    "            # 这样encoder_outputs每一行存的都是对应的句子中每个单词通过编码器的输出结果\n",
    "            encoder_outputs[ei] += encoder_output[0, 0]\n",
    "\n",
    "        # 初始化解码器的第一个输入，即起始符\n",
    "        decoder_input = torch.tensor([[SOS_token]], device=device) \n",
    "        # 初始化解码器的隐层张量即编码器的隐层输出\n",
    "        decoder_hidden = encoder_hidden\n",
    "\n",
    "        # 初始化预测的词汇列表\n",
    "        decoded_words = []\n",
    "        # 初始化attention张量\n",
    "        decoder_attentions = torch.zeros(max_length, max_length)\n",
    "        # 开始循环解码\n",
    "        for di in range(max_length):\n",
    "            # 将decoder_input, decoder_hidden, encoder_outputs传入解码器对象\n",
    "            # 获得decoder_output, decoder_hidden, decoder_attention\n",
    "            decoder_output, decoder_hidden, decoder_attention = decoder(\n",
    "                decoder_input, decoder_hidden, encoder_outputs)\n",
    "\n",
    "            # 取所有的attention结果存入初始化的attention张量中\n",
    "            decoder_attentions[di] = decoder_attention.data\n",
    "            # 从解码器输出中获得概率最高的值及其索引对象\n",
    "            topv, topi = decoder_output.data.topk(1)\n",
    "            # 从索引对象中取出它的值与结束标志值作对比\n",
    "            if topi.item() == EOS_token:\n",
    "                # 如果是结束标志值，则将结束标志装进decoded_words列表，代表翻译结束\n",
    "                decoded_words.append('<EOS>')\n",
    "                # 循环退出\n",
    "                break\n",
    "\n",
    "            else:\n",
    "                # 否则，根据索引找到它在输出语言的index2word字典中对应的单词装进decoded_words\n",
    "                decoded_words.append(output_lang.index2word[topi.item()])\n",
    "\n",
    "            # 最后将本次预测的索引降维并分离赋值给decoder_input，以便下次进行预测\n",
    "            decoder_input = topi.squeeze().detach()\n",
    "        # 返回结果decoded_words， 以及完整注意力张量, 把没有用到的部分切掉\n",
    "        return decoded_words, decoder_attentions[:di + 1]\n"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 随机选择指定数量的数据进行评估"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "source": [
    "def evaluateRandomly(encoder, decoder, n=6):\n",
    "    \"\"\"随机测试函数, 输入参数encoder, decoder代表编码器和解码器对象，n代表测试数\"\"\"\n",
    "    # 对测试数进行循环\n",
    "    for i in range(n):\n",
    "        # 从pairs随机选择语言对\n",
    "        pair = random.choice(pairs)\n",
    "        # > 代表输入\n",
    "        print('>', pair[0])\n",
    "        # = 代表正确的输出\n",
    "        print('=', pair[1])\n",
    "        # 调用evaluate进行预测\n",
    "        output_words, attentions = evaluate(encoder, decoder, pair[0])\n",
    "        # 将结果连成句子\n",
    "        output_sentence = ' '.join(output_words)\n",
    "        # < 代表模型的输出\n",
    "        print('<', output_sentence)\n",
    "        print('')"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [
    "# 调用验证\n",
    "# 调用evaluateRandomly进行模型测试，将编码器对象encoder1，码器对象attn_decoder1传入其中\n",
    "evaluateRandomly(encoder1, attn_decoder1)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attention张量制图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "source": [
    "sentence = \"we re both teachers .\"\n",
    "# 调用评估函数\n",
    "output_words, attentions = evaluate(\n",
    "encoder1, attn_decoder1, sentence)\n",
    "print(output_words)\n",
    "# 将attention张量转化成numpy, 使用matshow绘制\n",
    "plt.matshow(attentions.numpy())\n",
    "# 保存图像\n",
    "plt.savefig(\"./s2s_attn.png\")"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [],
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
